#include "cmsis_os.h"
#include "oled.h"
#include "rs485.h"
#include "task_sensor.h"
#include "task_display.h"
#include "usart.h"
#include "stop2.h"


extern osMessageQueueId_t batteryQueueHandle;   //电池队列
extern osMessageQueueId_t sensorQueueHandle;    //传感器队列

extern u8g2_t u8g2;
extern volatile uint8_t ml307_rx_byte;


/**
  * @brief  Display task function
  * @param  argument: Pointer to task arguments
  * @retval None
  */

void Display_Task(void *argument) {
  (void)argument;  // 防止未使用的参数警告
  Display_BootAnimation();

  for(;;) {
    // 等待任务通知，有多个标志可以触发任务
    osThreadFlagsWait(0x01, osFlagsWaitAny, osWaitForever);

    BatteryData_t batteryData;
    SensorQueue_t sensorData;

    // 尝试从队列获取数据，增加超时处理，避免长时间阻塞
    if (osMessageQueueGet(batteryQueueHandle, &batteryData, NULL, osWaitForever) == osOK &&
        osMessageQueueGet(sensorQueueHandle, &sensorData, NULL, osWaitForever) == osOK) {

      // 直接处理和显示数据
      float batt = batteryData.percentage;
      float temp = sensorData.temperature;
      float humi = sensorData.humidity;
      float ec = sensorData.EC;

      Display_MainScreen(batt, temp, humi, ec);
        }
    else {
      // 错误处理，确保队列读取成功

    }

    //------------------------进入stop2模式-------------------------
    // 保持亮屏 10 秒
    osDelay(10000);

    // 灭屏
    u8g2_SetPowerSave(&u8g2, 1);


    // 进入 Stop2 (下一次由 RTC / 按键 / LPUART 唤醒)
    HAL_UART_Receive_IT(&hlpuart1, (uint8_t *)&ml307_rx_byte, 1); // 确保 LPUART 能唤醒
    HAL_PWREx_EnterSTOP2Mode(PWR_STOPENTRY_WFI);

    stop2_wake_init();

  }
}

